package com.neusoft.dao.impl;

import com.neusoft.dao.UserDao;
import com.neusoft.db.DBManager;
import com.neusoft.db.JdbcTemplate;
import com.neusoft.mapping.EntityMapping;
import com.neusoft.mapping.MappingFactory;
import com.neusoft.model.User;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class UserDaoImpl extends BaseDao implements UserDao {

    @Override
    public User login(String username, String password) {
        String sql = "select * from user where username=? and password=?";
        EntityMapping mapping = mappingFactory.getMapping(MappingFactory.USER_MAPPING);
        List<Object> list = jt.query(sql,mapping,username,password);
        if(list.size()>0){ //如果集合中有User这个对象
            User user = (User) list.get(0); //从list集合中获取到这个元素（User对象）
            return user;
        }
        return null;
    }

    @Override
    public boolean register(User user) throws SQLException {
        String sql = "insert into user(username,password) values(?,?)";
        int isRight = jt.update(sql, user.getUsername(), user.getPassword());
        return isRight == 1;
    }

    public static void main(String[] args) {
        UserDao userDao = new UserDaoImpl();
        User user = userDao.login("admin","123456");
        System.out.println(user.getUsername());
    }



    @Override
    public List<User> getUsers() {
        List<User> users = new ArrayList<User>();
        String sql = "select * from user";
        EntityMapping mapping = mappingFactory.getMapping(MappingFactory.USER_MAPPING);
        List<Object> list = jt.query(sql,mapping);
        for(int i=0;i<list.size();i++){
            User user = (User) list.get(i);
            //向新的容器中添加用户对象
            users.add(user);
        }
        return users;
    }

    @Override
    public User findUserById(int id) {
        User user = null;
        String sql = "select * from user where id=?";
        EntityMapping mapping = mappingFactory.getMapping(MappingFactory.USER_MAPPING);
        List<Object> list = jt.query(sql,mapping,id);
        if(list.size()>0){
             user = (User) list.get(0);
        }
        return user;
    }

    @Override
    public boolean updateUser(User user) throws SQLException {
        String sql = "update user set username=?,password=? where id=?";
        int isRight = jt.update(sql,user.getUsername(),user.getPassword(),user.getId());
        return isRight == 1;
    }

    @Override
    public boolean deleteUser(int id) throws SQLException {
        String sql = "delete from user where id=?";
        int isRight = jt.update(sql,id);
        return isRight == 1;
    }


}
